# -*- coding: utf-8 -*-


"""
Adding a player screen.

It can change Game Phase from Phase.ADD_PLAYER to Phase.ADD_WORDS
Pressing the button "Add player" -> going to screen "Add_words".

I needs valid list of users (gamestate.players.players)
It will add Player object to list of users (gamestate.players.players)
"""

from kivy.app import App
from kivy.event import EventDispatcher
from kivy.properties import StringProperty, BooleanProperty, ObjectProperty
from model.gamestate import *
from ui.hat_widget import HatWidget


class AddPlayerScreenState(EventDispatcher):
    player_name = StringProperty()
    name_valid = BooleanProperty()

    def __init__(self, game_state):
        self.game_state = game_state
        self.player_name = ''
        self.name_valid = False

    def update_name(self, name):
        self.player_name = name
        name = name.strip()

        valid = (name != '')
        for i in self.game_state.players.players:
            valid = valid and (i.name != name)

        self.name_valid = valid

    def add_user(self):
        self.game_state.current_added_player =\
            Player(self.player_name.strip(), [])


class AddPlayerScreen(HatWidget):
    state = ObjectProperty(None)

    def __init__(self, game_state, presenter, **kwargs):
        """ Drawing screen which will be used for adding a player
        args:
            game_state: gamestate for the moment of launching
            presenter: current presenter

        """
        self.state = AddPlayerScreenState(game_state)
        super(AddPlayerScreen, self).__init__(presenter, **kwargs)

    def update_name(self, value):
        self.state.update_name(value)

    def on_add_user_pressed(self):
        """ Called when button "Add user" is pressed". Adds user in gamestate.

            -puts in players the name of the user
            -puts him also to the current_added_player
        """
        if not self.to_add_button.enabled:
            return
        self.state.add_user()
        self.presenter.change_phase(Phase.ADD_WORDS)

    def go_back(self):
        self.presenter.change_phase(Phase.JOIN if
                                    self.state.game_state.is_joining
                                    else Phase.START_GAME)
